package com.example.xgakj.newterminal.pushmodule;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.xgakj.mylibrary.mvp.utils.CommonUtil;
import com.example.xgakj.mylibrary.mvp.utils.SharedPreferencesUtil;
import com.example.xgakj.mylibrary.mvp.utils.ToastUtil;
import com.example.xgakj.newterminal.R;
import com.example.xgakj.newterminal.base.BaseApplication;
import com.example.xgakj.newterminal.base.Parameters;
import com.example.xgakj.newterminal.beans.AlarmInfoBean;
import com.example.xgakj.newterminal.beans.AlarmTable;
import com.example.xgakj.newterminal.beans.DeviceBean;
import com.example.xgakj.newterminal.ui.activities.LoginActivity;
import com.example.xgakj.newterminal.ui.framents.AlarmDetailFragment;
import com.jovision.demo.Play2Activity;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.socks.library.KLog;
import com.tutk.sample.AVAPI.MainActivity2;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;


public class MessageActivity extends AppCompatActivity {

    @BindView(R.id.tv_message)
    TextView tvMessage;
    @BindView(R.id.btn_video)
    Button btnVideo;
    @BindView(R.id.btn_details)
    Button btnDetails;
    @BindView(R.id.btn_cancel)
    Button btnCancel;
    MediaPlayer mp;
    @BindView(R.id.btn_goLogin)
    Button btnGoLogin;
    @BindView(R.id.mainFrame)
    RelativeLayout mainFrame;
    @BindView(R.id.topbar)
    QMUITopBar topbar;
    private Vibrator vibrator;
    String mac = null;
    String id = null;
    String type = null;
    String str = null;
    String ssn = null;
    long startTime;
    private boolean isJump;
    private String field, param_filter, tableName;
    private AlarmInfoBean alarmInfoBean;
    private String deviceAddress;
    private String devicePwd;
    private int ifaddr;
    private DeviceBean mDevice;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Window win = getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_message);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initTopbar();
        startTime = System.currentTimeMillis() / 1000;
        field = "id,dateon,custid,partid,jqneirong,jingqingid,fangqu,note,ifok,disposal,clientok,itype";
        alarmInfoBean = (AlarmInfoBean) getIntent().getSerializableExtra(Parameters.VIEW_YUYINALARMLOGS);
        showInfo(alarmInfoBean);
        noticeAlarm();
        btnGoLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MessageActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });

    }

    private void initTopbar() {
        topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();

                overridePendingTransition(R.anim.slide_still, R.anim.slide_out_right);
            }
        });
        topbar.setTitle("报警信息");
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (CommonUtil.isNull(BaseApplication.ssn)) {
            btnGoLogin.setVisibility(View.VISIBLE);
        } else {
            btnGoLogin.setVisibility(View.INVISIBLE);
        }
    }

    private void noticeAlarm() {
        if (SharedPreferencesUtil.getBoolean(MessageActivity.this, Parameters.ALARM_VIBRATE, true)) {
            vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
            // Vibrate for 500 milliseconds
            vibrator.vibrate(6000);
        }

        if (SharedPreferencesUtil.getBoolean(MessageActivity.this, Parameters.ALARM_MUSIC, true)) {
            String path = SharedPreferencesUtil.getString(MessageActivity.this, Parameters.MUSIC, "");
            KLog.e("shurun", path + "**");

            try {
                if (path.equals("")) {
                    mp = MediaPlayer.create(MessageActivity.this, R.raw.alarmmusic);
                    mp.start();
                } else {
                    mp = new MediaPlayer();
                    mp.setDataSource(path);
                    mp.prepare();
                    mp.start();
                }


            } catch (IOException e) {
                e.printStackTrace();
            }
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.start();
                    if (System.currentTimeMillis() / 1000 - startTime > 60) {
                        cancelAlarm();
                        finish();
                    }
                }
            });
        }
    }
/*

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        cancelAlarm();
        alarmInfoBean = (AlarmInfoBean) intent.getSerializableExtra(Constants.ALARM);
        showInfo(alarmInfoBean);
        startTime = System.currentTimeMillis() / 1000;
        noticeAlarm();
    }
*/

    private void showInfo(AlarmInfoBean infoBean) {
        String event = infoBean.getJQNeiRong();
        String area = infoBean.getFangqu();
        String time = infoBean.getDateOn();
        str = "防区:" + area + "  " + "事件：" + event + "  " + "时间：" + time;
        tvMessage.setText(str);

    }

    public void jump(View view) {
        switch (view.getId()) {
            case R.id.btn_cancel:
                cancelAlarm();
                isJump = false;
                finish();
                break;
            case R.id.btn_details:
//                ToastUtil.showToast(MessageActivity.this, "btn_details");
                cancelAlarm();
                if (CommonUtil.isNull(BaseApplication.ssn)) {
                    ToastUtil.showShort(MessageActivity.this, "请登录后查看");
                    return;
                }

                Bundle bundle = new Bundle();
                AlarmTable alarmTable = changeAlarm(alarmInfoBean);
                bundle.putSerializable(Parameters.ALARM_BEAN, alarmTable);
                AlarmDetailFragment detailFragment = new AlarmDetailFragment();
                detailFragment.setArguments(bundle);
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.mainFrame, detailFragment).commit();

                break;
            case R.id.btn_video:
                cancelAlarm();
                isJump = false;
                if (!CommonUtil.isNull(BaseApplication.ssn)) {
                    if (ifaddr == Parameters.TUTK) {
                        if (CommonUtil.isNull(mDevice.getAddress())){
                            ToastUtil.showShort(MessageActivity.this,"该设备没有视频设备");
                        }
                        Intent intent2 = new Intent(MessageActivity.this, MainActivity2.class);
                        intent2.putExtra(Parameters.VIDEO_UID, mDevice.getAddress());
                        intent2.putExtra(Parameters.VIDEO_PASSWORD, mDevice.getPwd());
                        startActivity(intent2);
                    } else if (ifaddr == Parameters.YUN_SHI_TONG) {
                        Intent intent = new Intent(MessageActivity.this, Play2Activity.class);
                        intent.putExtra("deviceBean", mDevice);
                        startActivity(intent);
                    } else {
                        ToastUtil.showShort(MessageActivity.this, "不支持该设备视频格式");
                    }

                    finish();
                } else {
                    ToastUtil.showShort(MessageActivity.this, "请登录");
                }

                break;
            default:

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onQueryDevice(DeviceBean device) {
        deviceAddress = device.getAddress();
        devicePwd = device.getPwd();
        KLog.e(deviceAddress + "*" + devicePwd);
        ifaddr = device.getIfaddr();
        mDevice = device;

    }

    private AlarmTable changeAlarm(AlarmInfoBean alarmInfoBean) {
        AlarmTable alarmTable = new AlarmTable();
        alarmTable.setClientok(alarmInfoBean.getClientOK());
        alarmTable.setCustid(alarmInfoBean.getCustID());
        alarmTable.setDateon(alarmInfoBean.getDateOn());
        alarmTable.setDisposal(alarmInfoBean.getDisposal());
        alarmTable.setFangqu(alarmInfoBean.getFangqu());
        alarmTable.setId(alarmInfoBean.getId());
        alarmTable.setIfok(alarmInfoBean.getIfok());
        alarmTable.setJingqingid(alarmInfoBean.getId());
        alarmTable.setNote(alarmInfoBean.getNote());
        alarmTable.setItype(alarmInfoBean.getItype());
        alarmTable.setPartid(alarmInfoBean.getPartid());
        alarmTable.setJqneirong(alarmInfoBean.getJQNeiRong());

        return alarmTable;
    }

    private void cancelAlarm() {
        if (mp != null) {
            mp.setOnCompletionListener(null);
            mp.stop();
            mp.release();
            mp = null;
        }

        if (vibrator.hasVibrator()) {
            vibrator.cancel();
        }

    }


    @Override
    protected void onStop() {
        super.onStop();
//        cancelAlarm();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}